import React from 'react';
import { Icon, Input, Button, Table, Pagination, Modal, message } from 'antd';
import AddForm from './Creat';
import './index.less';
import axios from 'axios';
import Tips from '../Tips/index';
import JoinNetWork from './Join';
import Detail from './detail';
import Invite from './invite';
import { connect } from 'react-redux';
import statuscode from '../statuscode/index';
import Bread from '../common/Bread/index';
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';

var networkstatus = {
  1000: '创建中',
  1010: '创建成功',
  1020: '创建失败',
  2000: '启动中',
  2010: '启动成功',
  2020: '启动失败',
  3000: '停止中',
  3010: '已停止',
  2030: '启动失败',
  3020: '停止失败',
  20: '审批中',
  30: '加入中',
  40: '加入中',
  51: '加入失败',
  52: '加入失败',
  41: '加入失败'
};
class Net extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      date: '',
      data: [],
      page: 1,
      limit: 10,
      totalnum: 0,
      message: '',
      update: false,
      visible: false,
      joinnetworkvisible: false,
      textdatanet: '',
      timeout: false
    };
  }
  componentWillMount() {
    this.ismounted = true;
    setTimeout(() => {
      this.getData(this.state.page, this.state.limit);
    });
  }
  componentWillUnmount() {
    this.ismounted = false;
  }
  componentWillUpdate(nextprops) {
    if (nextprops.changeOrgid != this.props.changeOrgid) {
      this.getData(this.state.page, this.state.limit, nextprops.changeOrgid);
    }
  }
  handleCancel = () => {
    this.setState({
      visiblestartnet: false,
      visiblestopnet: false,
      visiblejoinnet: false
    });
  }
  approval = text => {
    this.setState({
      message: 'loading'
    });
    var $this = this;
    var data = {
      networkName: text.networkname,
      orgId: this.props.changeOrgid
    };
    const Token = localStorage.getItem('token');
    axios
      .post('/api/block/network/checkNetworkAdmin', data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: Token
        }
      })
      .then(function(response) {
        if ($this.ismounted) {
          var code = response.data.code;
          if (statuscode[response.data.code] == undefined) code = 500;
          var message = statuscode[code];
          if (!response.data.data) message = '您不是网络管理员！';
          $this.setState(
            {
              message: message
            },
            () => {
              setTimeout(() => {
                if (response.data.data) {
                  $this.props.dispatch({
                    type: 'clicknetwork',
                    clicknetwork: text.networkname
                  });
                  $this.props.history.push('/Net/ApprovalRecord');
                  localStorage.setItem('clicknetworkapproval', text.networkname);
                }
                $this.setState({
                  message: ''
                });
              }, 1000);
            }
          );
        }
      });
  }
  columns = [
    {
      title: '名称',
      dataIndex: '名称',
      key: '名称'
      // width: 140,
    },
    {
      title: 'Peer节点数',
      dataIndex: 'Peer节点数',
      key: 'Peer节点数'
      // width: 100,
    },
    {
      title: 'Orderer节点数',
      dataIndex: 'Orderer节点数',
      key: 'Orderer节点数'
      // width: 100,
    },
    {
      title: '备注',
      dataIndex: '备注',
      key: '备注',
      width: 300
    },
    {
      title: '状态',
      dataIndex: '状态',
      key: '状态'
      // width: 100,
    },
    {
      title: '控制网络',
      key: '控制网络',
      // width: 230,
      render: (text, record) => (
        <span className="controlnet">
          <span
            className={record['状态'] == '启动成功' ? 'disablednone' : 'startnet'}
            style={{ display: record['状态'] == '启动成功' || record.permission != 1 ? 'none' : '' }}
            size="small"
            onClick={this.startnetvisble.bind(this, text, record)}
          >
            启动
          </span>
          <span
            className="stopnet"
            size="small"
            onClick={this.stopnetvisble.bind(this, text, record)}
            style={{ display: record['状态'] == '启动成功' && record.permission == 1 ? '' : 'none' }}
          >
            停止
          </span>
          <span
            disabled
            className="joinnet"
            size="small"
            onClick={this.joinnetvisble.bind(this, text, record)}
            style={{ display: record.permission == 2 ? '' : 'none' }}
          >
            加入该网络
          </span>
        </span>
      )
    },
    {
      title: '其他操作',
      key: '其他操作',
      // width: 230,
      render: (text, record) => (
        <span className="controlnet">
          <span className="datailnet" size="small" onClick={this.detailshowModal.bind(this, text, record)}>
            详情
          </span>
          {/* <span className="invitenet" size="small" onClick={this.inviteshowModal.bind(this, text, record)} >邀请组织</span> */}
          <span className="appoavalnet" size="small" onClick={this.approval.bind(this, text, record)} style={{ display: record['状态'] == '启动成功' && record.permission == 1 ? '' : 'none' }}>
            审批记录
          </span>
        </span>
      )
    }
  ]
  stateData = {
    page: ['10', '20', '30', '40', '50', '60', '70', '80', '90']
  }

  showModal = () => {
    this.setState({
      visible: true
    });
  }
  handleChancel = () => {
    this.setState({
      visible: false
    });
  }
  stopnetvisble = (text, i) => {
    this.setState({
      visiblestopnet: true,
      textdatanet: text
    });
  }
  startnetvisble = (text, i) => {
    if (text['状态'] == '启动成功' || i == '启动成功') return;
    this.setState({
      visiblestartnet: true,
      textdatanet: text
    });
  }
  joinnetvisble = (text, i) => {
    this.setState({
      visiblejoinnet: true,
      textdatanet: text
    });
  }
  handleCreate = _this => {
    var $this = this;
    _this.props.form.validateFields((err, values) => {
      if (!err) {
        this.setState({ timeout: true, message: 'loading' });
        setTimeout(() => {
          this.setState({ timeout: false });
        }, 5000);
        const Token = localStorage.getItem('token');
        var data = {
          peerNum: values.peerNum,
          networkName: values.networkName,
          nickname: values.nickname,
          // ordererNum: values.ordererNum,
          ordererNum: '2',
          remark: values.remark,
          fabricFlag: 'fabric_default',
          channelId: 'mychannel',
          orgId: this.props.changeOrgid
        };
        axios
          .post('/api/block/network/createNetWork', data, {
            headers: {
              'Content-Type': 'application/json',
              Authorization: Token
            }
          })
          .then(function(response) {
            if ($this.ismounted) {
              var code = response.data.code;
              if (statuscode[response.data.code] == undefined) code = '500';
              var message = statuscode[code];
              $this.setState({
                message: message,
                visible: code == '200' ? false : true
              });
              setTimeout(() => {
                if (code == 200) {
                  $this.getData($this.state.page, $this.state.limit);
                }
                $this.setState({
                  message: ''
                });
              }, 1000);
            }
          });
      } else {
        console.log('Received values of form: ', values);
      }
    });
  }
  joinnetworkshowModal = () => {
    this.setState({
      joinnetworkvisible: true
    });
  }
  joinnetworkhandleChancel = () => {
    this.setState({
      joinnetworkvisible: false
    });
  }
  joinnetworkhandleCreate = _this => {
    const $this = this;
    _this.props.form.validateFields((err, values) => {
      if (!err) {
        this.setState({
          message: 'loading'
        });
        const Token = localStorage.getItem('token');
        var data = {
          invitation: values.invitation,
          orgId: this.props.changeOrgid,
          remark: values.remark
        };
        axios
          .post('/api/block/network/registerNetwork', data, {
            headers: {
              'Content-Type': 'application/json',
              Authorization: Token
            }
          })
          .then(function(response) {
            if ($this.ismounted) {
              var code = response.data.code;
              if (statuscode[response.data.code] == undefined) code = '500';
              var message = statuscode[code];
              if (code == 200) message = '请求已发送';
              $this.setState({
                message: message,
                joinnetworkvisible: code == '200' ? false : true
              });
              setTimeout(() => {
                if (code == 200) {
                  $this.props.dispatch({
                    type: 'updatenet',
                    onoff: true
                  });
                  $this.getData($this.state.page, $this.state.limit);
                }
                $this.setState({
                  message: ''
                });
              }, 1000);
            }
          });
      } else {
        console.log('Received values of form: ', values);
      }
    });
  }
  detailshowModal = text => {
    const _this = this;
    this.setState({
      message: 'loading'
    });
    var Token = localStorage.getItem('token');
    axios({
      method: 'get',
      url: '/api/block/network/queryBaasNetwork',
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token
      },
      params: { networkName: text.networkname }
    }).then(function(response) {
      if (_this.ismounted) {
        var code = response.data.code;
        if (statuscode[response.data.code] == undefined) code = '500';
        var message = statuscode[code];
        _this.setState(
          {
            detailvisible: true,
            title: text['名称'],
            detaildata: response.data.data,
            message: message
          },
          () => {
            setTimeout(() => {
              _this.setState({
                message: ''
              });
            }, 1000);
          }
        );
      }
    });
  }
  detailhandleChancel = () => {
    this.setState({
      detailvisible: false
    });
  }
  inviteshowModal = text => {
    const Token = localStorage.getItem('token');
    this.setState({
      message: 'loading'
    });
    const _this = this;
    var networkName = text.networkname ? text.networkname : text.networkName;
    axios({
      method: 'get',
      url: '/api/block/network/queryBaasNetworkByAdmin',
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token
      },
      params: { networkName: networkName }
    }).then(function(response) {
      if (_this.ismounted) {
        var code = response.data.code;
        if (statuscode[response.data.code] == undefined) code = '500';
        var message = statuscode[code];
        if (code == 200) {
          _this.setState(
            {
              invitevisible: true,
              detailvisible: false,
              title: text.networkname,
              invitationdata: response.data.data,
              message: ''
            },
            () => {
              setTimeout(() => {
                _this.setState({
                  message: ''
                });
              }, 1000);
            }
          );
        } else {
          _this.setState(
            {
              // detailvisible: false,
              message: message
            },
            () => {
              setTimeout(() => {
                _this.setState({
                  message: ''
                });
              }, 1000);
            }
          );
        }
      }
    });
  }

  invitehandleChancel = () => {
    this.setState({
      invitevisible: false
    });
  }
  onShowSizeChange = (current, pageSize) => {
    this.getData(current, pageSize);
    this.setState({
      limit: pageSize,
      page: current
    });
  }
  onChange = pageNumber => {
    this.getData(pageNumber);
  }
  changesearch = ev => {
    this.setState({ searchvalue: ev.target.value });
  }
  search = () => {
    this.getData(this.state.page, this.state.limit, this.props.changeOrgid, this.state.searchvalue);
  }
  start = (text, i) => {
    var text = this.state.textdatanet;
    this.setState({
      message: 'loading'
    });
    var _this = this;
    const Token = localStorage.getItem('token');
    var networkName = text.networkname ? text.networkname : text;
    var data = {
      networkName: networkName,
      orgId: this.props.changeOrgid
    };
    axios
      .post('/api/block/network/startNetWork', data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: Token
        }
      })
      .then(function(response) {
        if (_this.ismounted) {
          var code = response.data.code;
          if (statuscode[response.data.code] == undefined) code = '500';
          var message = statuscode[code];
          _this.setState(
            {
              message: message
            },
            () => {
              setTimeout(() => {
                if (code == 200) {
                  _this.props.dispatch({
                    type: 'updatenet',
                    onoff: true
                  });
                  _this.getData(_this.state.page, _this.state.limit);
                  _this.setState({ visiblestartnet: false });
                }
                _this.setState({
                  message: ''
                });
              }, 1000);
            }
          );
        }
      });
  }

  stop = text => {
    var text = this.state.textdatanet;
    this.setState({
      message: 'loading'
    });
    const Token = localStorage.getItem('token');
    var networkName = text.networkname ? text.networkname : text;
    var data = {
      networkName: networkName,
      orgId: this.props.changeOrgid
    };
    var _this = this;
    axios
      .post('/api/block/network/stopNetWork', data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: Token
        }
      })
      .then(function(response) {
        if (_this.ismounted) {
          var code = response.data.code;
          if (statuscode[response.data.code] == undefined) code = '500';
          var message = statuscode[code];
          _this.setState(
            {
              message: message
            },
            () => {
              setTimeout(() => {
                if (code == 200) {
                  _this.getData(_this.state.page, _this.state.limit);
                  _this.setState({ visiblestopnet: false });
                }
                _this.setState({
                  message: ''
                  // detailvisible:false
                });
              }, 1000);
            }
          );
        }
      });
  }

  join = () => {
    var text = this.state.textdatanet;
    const _this = this;
    var networkName = text.networkname;
    var data = {
      FabricFlag: networkName,
      OrgId: this.props.changeOrgid,
      RequestType: 'RegisterUserReq',
      ChannelId: 'mychannel'
    };
    this.setState({
      message: 'loading'
    });
    var Token = localStorage.getItem('token');
    axios
      .post('/api/block/network/registerUser', data, {
        headers: {
          'Content-Type': 'application/json',
          Authorization: Token
        }
      })
      .then(function(response) {
        if (_this.ismounted) {
          var code = response.data.code;
          if (statuscode[response.data.code] == undefined) code = '500';
          var message = statuscode[code];
          _this.setState({
            message: message
          });
          setTimeout(() => {
            if (code == 200) {
              _this.props.dispatch({
                type: 'updatenet',
                onoff: true
              });
              setTimeout(() => {
                _this.getData(_this.state.page, _this.state.limit);
                _this.setState({ visiblejoinnet: false });
              });
            }
            _this.setState({
              message: ''
            });
          }, 1000);
        }
      });
  }

  getData = (page, limit = this.state.limit, changeOrgid = this.props.changeOrgid, searchdata) => {
    if (!changeOrgid) return;
    const $this = this;
    this.setState({
      message: 'loading'
    });
    const Token = localStorage.getItem('token');
    axios({
      method: 'get',
      url: '/api/block/network/queryNetWorkList',
      headers: {
        'Content-Type': 'application/json',
        Authorization: Token
      },
      params: { page: page, limit: limit, orgId: changeOrgid, nickname: searchdata }
    }).then(function(response) {
      if ($this.ismounted) {
        var code = response.data.code;
        // if (statuscode[response.data.code] == undefined) code = '500'
        var message = statuscode[code];
        let data = [];
        response.data &&
          response.data.data &&
          response.data.data.rows &&
          response.data.data.rows.forEach((e, i) => {
            data.push({
              key: String(i),
              名称: e.nickname,
              Peer节点数: e.peerNum,
              Orderer节点数: e.ordererNum,
              备注: e.remark,
              状态: networkstatus[e.networkStatus],
              networkname: e.networkName,
              permission: e.permission
            });
          });
        $this.setState(
          {
            data: data,
            totalnum:
              response.data && response.data.data && response.data.data.total
                ? response.data.data.total
                : 0,
            message: message
          },
          () => {
            setTimeout(() => {
              $this.setState({
                message: ''
              });
            }, 1000);
          }
        );
      }
    });
  }
  render() {
    return (
      <div>
        <Bread bread={['网络管理', ['网络管理', 'net']]} />
        <div className="index-buttons">
          <Button type="primary" onClick={this.showModal} disabled={this.props.changeOrgid ? false : true}>
            创建一个网络
          </Button>
          {/* <Button type="Default" style={{ marginLeft: 10 }} onClick={this.joinnetworkshowModal} disabled={this.props.changeOrgid ? false : true}>加入一个网络</Button> */}
        </div>
        {/* {joinnet} */}
        <div className="inviteUserBox">
          <Input placeholder="请输入网络名称" className="input" onChange={this.changesearch} />
          <Button type="primary" className="search" onClick={this.search}>
            <img src={require('./../../static/img/search_icon.png')} />
          </Button>
        </div>
        <Table
          className="netTable"
          columns={this.columns}
          dataSource={this.state.data}
          bordered
          Paginatio={this.onShowSizeChange}
          pagination={false}
        />
        <div className="page_foot">
          <span className="data_num">共{this.state.totalnum}条</span>
          <Pagination
            pageSizeOptions={this.stateData.page}
            className="page"
            showSizeChanger
            showQuickJumper
            onShowSizeChange={this.onShowSizeChange}
            defaultCurrent={1}
            total={this.state.totalnum}
            onChange={this.onChange}
          />
        </div>
        <AddForm
          visible={this.state.visible}
          onCancel={this.handleChancel}
          onCreate={this.handleCreate}
          timeout={this.state.timeout}
        />
        <JoinNetWork
          visible={this.state.joinnetworkvisible}
          onCancel={this.joinnetworkhandleChancel}
          onCreate={this.joinnetworkhandleCreate}
        />
        <Detail
          visible={this.state.detailvisible}
          stop={this.stopnetvisble}
          onCancel={this.detailhandleChancel}
          title={this.state.title}
          // onCreate={this.detailhandleCreate}
          inviteshowModal={this.inviteshowModal}
          start={this.startnetvisble}
          detaildata={this.state.detaildata}
        />
        <Invite
          visible={this.state.invitevisible}
          onCancel={this.invitehandleChancel}
          title={this.state.title}
          invitationdata={this.state.invitationdata}
        />
        <Modal
          style={{ zIndex: 1000 }}
          visible={this.state.visiblestartnet}
          title="提示"
          iconType="warning"
          onCancel={this.handleCancel}
          closable={false}
          footer={[
            <Button key="back" onClick={this.handleCancel}>
              取消
            </Button>,
            <Button key="submit" type="primary" onClick={this.start}>
              确定
            </Button>
          ]}
        >
          <p className="textAlign_D">
            <span className="CommonTips">
              您是否确认开启网络：{' '}
              {this.state.textdatanet['名称'] ? this.state.textdatanet['名称'] : this.state.textdatanet}
            </span>
          </p>
        </Modal>
        <Modal
          style={{ zIndex: 1000 }}
          visible={this.state.visiblestopnet}
          title={[<Icon type="warning" key={'1'} style={{ color: 'orange' }} />, <span key={2}>&nbsp;提示</span>]}
          iconType="warning"
          onCancel={this.handleCancel}
          closable={false}
          footer={[
            <Button key="back" onClick={this.handleCancel}>
              取消
            </Button>,
            <Button key="submit" type="primary" onClick={this.stop}>
              确定
            </Button>
          ]}
        >
          <p className="textAlign_D">
            <span className="CommonTips">
              请确认是否要停止网络，确定后当前的区块链网络环境将被删除，您的历史交易数据将全部被清除。如确认操作请点击“确定”按钮，否则请点击“取消”按钮退出。{/* {this.state.textdatanet['名称'] ? this.state.textdatanet['名称'] : this.state.textdatanet} */}
            </span>
          </p>
        </Modal>
        <Modal
          style={{ zIndex: 1000 }}
          visible={this.state.visiblejoinnet}
          title="提示"
          iconType="warning"
          onCancel={this.handleCancel}
          closable={false}
          footer={[
            <Button key="back" onClick={this.handleCancel}>
              取消
            </Button>,
            <Button key="submit" type="primary" onClick={this.join}>
              确定
            </Button>
          ]}
        >
          <p className="textAlign_D">
            <span className="CommonTips">
              您是否确认加入网络：{this.state.textdatanet['名称']
                ? this.state.textdatanet['名称']
                : this.state.textdatanet}
            </span>
          </p>
        </Modal>
        <Tips message={this.state.message} />
      </div>
    );
  }
}

export default connect(state => {
  return { ...state };
})(Net);
